package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import com.example.demo.dto.UserDTO;
import com.example.demo.vo.UserVO;
import com.example.demo.common.ApiResult;
import com.mybatisflex.core.paginate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 分页查询用户
     */
    @GetMapping
    public ApiResult<Page<User>> getUserPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword) {
        Page<User> userPage = userService.paginateUser(page, size, keyword);
        return ApiResult.success(userPage);
    }

    /**
     * 根据ID获取用户
     */
    @GetMapping("/{id}")
    public ApiResult<User> getUserById(@PathVariable Long id) {
        User user = userService.getUserById(id);
        return ApiResult.success(user);
    }

    /**
     * 创建用户
     */
    @PostMapping
    public ApiResult<Void> createUser(@RequestBody UserDTO userDTO) {
        userService.createUser(userDTO);
        return ApiResult.success();
    }

    /**
     * 更新用户
     */
    @PutMapping("/{id}")
    public ApiResult<Void> updateUser(@PathVariable Long id, @RequestBody UserDTO userDTO) {
        userDTO.setId(id);
        userService.updateUser(userDTO);
        return ApiResult.success();
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public ApiResult<Void> deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return ApiResult.success();
    }

    /**
     * 获取用户及余额信息
     */
    @GetMapping("/with-balance")
    public ApiResult<List<UserVO>> getUsersWithBalance() {
        List<UserVO> users = userService.listUsersWithBalance();
        return ApiResult.success(users);
    }

    /**
     * 根据部门查询用户
     */
    @GetMapping("/department")
    public ApiResult<List<User>> getUsersByDepartment(@RequestParam String deptName) {
        List<User> users = userService.getUsersByDepartment(deptName);
        return ApiResult.success(users);
    }
}